#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>

int main(int argc, char const *argv[])
{
    int buffer;
    pthread_rwlock_t rwlock;
    //初始化
    pthread_rwlock_init(&rwlock, NULL);

    //写锁(只允许一次一个写)
    pthread_rwlock_wrlock(&rwlock);
    buffer = 100;
    pthread_rwlock_unlock(&rwlock);

    //读锁（写时不能读，可以多个加锁读）
    pthread_rwlock_rdlock(&rwlock);
    printf("val(%d)\n", buffer);
    pthread_rwlock_unlock(&rwlock);

    //限时写锁
    struct timespec tout;
    clock_gettime(CLOCK_REALTIME, &tout);
    tout.tv_sec += 10;
    pthread_rwlock_timedwrlock(&rwlock, &tout);
    buffer = 200;
    pthread_rwlock_unlock(&rwlock);

    //限时读锁
    tout.tv_sec += 20;
    pthread_rwlock_timedrdlock(&rwlock, &tout);
    printf("val(%d)\n", buffer);
    pthread_rwlock_unlock(&rwlock);

    //尝试加锁
    pthread_rwlock_tryrdlock(&rwlock);
    pthread_rwlock_trywrlock(&rwlock);

    //销毁锁
    pthread_rwlock_destroy(&rwlock);
    return 0;
}
